package com.llap.exp190929.service;

import com.llap.exp190929.entity.Product;
import com.llap.exp190929.repository.ProductRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Slf4j
public class ProductService {
    private ProductRepository productRepository;

    public Product findProduct(int id) {
        return productRepository.findById(id).orElse(null);
    }

    public Page<Product> findProducts(int page, int pageSize, String keyword) {
        Pageable paginator = PageRequest.of(page - 1, pageSize);
        if (keyword == null || keyword.isEmpty()) {
            return productRepository.findAll(paginator);
        }
        return productRepository.findAllByNameLike("%" + keyword + "%", paginator);
    }

    public Page<Product> findProducts(int page, int pageSize) {
        return findProducts(page, pageSize, null);
    }

    @Transactional
    public Product addProduct(Product product) {
        if (product.getId() != null) return null;
        return productRepository.save(product);
    }

    @Transactional
    public Product updateProduct(Product product) {
        if (product.getId() == null) return null;
        return productRepository.save(product);
    }

    @Transactional
    public void deleteProduct(int id) {
        productRepository.deleteById(id);
    }
}
